package mypack.srverlet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import mypack.bean.Counter;

public class MyServletContextListener implements ServletContextListener{
    
	private final String PATH="D:/counter.txt";  
	
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		System.out.println("servlet context is destory ...");
		ServletContext  context = event.getServletContext();
		Counter counter = (Counter)context.getAttribute("counter");
		if(null==counter){
			counter = new Counter();
		}
		int count = counter.getCount();
		File f = new File(PATH);
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(f));
			bw.write(String.valueOf(count));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(bw!=null){
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
            
		System.out.println("servlet context is inited ...");
		ServletContext  context = event.getServletContext();
		File f = new File(PATH);
		
		if(!f.exists()){
			Counter counter = new Counter();
			context.setAttribute("counter", counter);
			return;
		}
		BufferedReader br =null;
		int count = 0;
		try {
			br = new BufferedReader(new FileReader(f));
			String line = null;
			while((line=br.readLine())!=null){
               	count = Integer.parseInt(line);			
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		Counter counter = new Counter(count);
		context.setAttribute("counter", counter);
	}

}
